<?php
/**
 * WebProduction Shop (wpshop)
 * @copyright (C) 2011-2012 WebProduction (tm) <webproduction.com.ua>
 *
 * This program is commercial software; you cannot redistribute it and/or
 * modify.
 */

/**
 * @author Maxim Miroshnichenko <max@webproduction.com.ua>
 * @copyright WebProduction
 * @package Shop
 */
class Datasource_Users extends Forms_ADataSourceSQLObject {

    public function __construct($groupID = false) {
        $this->_groupID = $groupID;
    }

    public function getSQLObject() {
        $users = BC::Get()->getUserService()->getUsersAll();
        if ($this->_groupID) {
            if (BC::Get()->getUserService()->isUserGroupOperationAllowed(new ShopUserGroup($this->_groupID), 'view')) {
                $users->setGroupid($this->_groupID);
            } else {
                $users->setGroupid(-1);
            }
        } else {
            if (BC::Get()->getUserService()->getUser()->getLevel() == 2) {
            	$groupsArray = BC::Get()->getUserService()->getUsersGroups('view');
                $groupIDs = array(0);
                foreach ($groupsArray as $group) {
                	$groupIDs[] = $group['id'];
                }
                $users->addWhereQuery('(`groupid` IN ('.implode(', ', $groupIDs).'))');
            }
        }
        return $users;
    }

    protected function _initialize() {
        $field = new Forms_ContentFieldInt('id');
        $field->setEditable(false);
        $field->setName('#');
        $this->_fieldsArray[] = $field;

        // gravatar
        $field = new Shop_ContentFieldGravatar('gravatar');
        $field->setName('Аватар');
        $field->setSortable(false);
        $field->setEditable(false);
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('login');
        $field->setName('Логин');
        $field->addValidator(new Forms_ValidatorLogin());
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentFieldPasswordMD5('password', true);
        $field->setName('Пароль');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('email');
        $field->setName('E-mail');
        //$field->addValidator(new Forms_ValidatorEmail());
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentFieldInt('level');
        $field->setName('Уровень доступа');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentFieldSelectList('groupid');
        $field->setDataSource(new Datasource_UserGroup());
        $field->setName('Группа');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('name');
        $field->setName('Ф.И.О.');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('phone');
        $field->setName('Телефон');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('address');
        $field->setName('Адрес');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentFieldSelectList('managerid', true);
        $field->setName('Менеджер');
        $field->setDataSource(new Datasource_Users());
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('department');
        $field->setName('Отдел');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentFieldTextarea('commentadmin');
        $field->setName('Скрытый комментарий администратора');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('cdate');
        $field->setEditable(false);
        $field->setName('Регистрация');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('adate');
        $field->setEditable(false);
        $field->setName('Активность');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentField('balance');
        $field->setEditable(false);
        $field->setName('Баланс');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentFieldInt('announcementsCountMonth');
        $field->setName('Количество объявлений<br /> в месяц');
        $this->_fieldsArray[] = $field;

        $field = new Forms_ContentFieldInt('announcementsCountWeek');
        $field->setName('Количество объявлений<br /> в неделю');
        $this->_fieldsArray[] = $field;
    }

    public function insert($fieldsArray) {
        try {
            SQLObject::TransactionStart();

            $r = parent::insert($fieldsArray);

            try {
                $user = BC::Get()->getUserService()->getUser();

                $x = BC::Get()->getUserService()->getUserByID($r);
                $x->setCdate(date('Y-m-d H:i:s'));
                $x->update();

                CommentsAPI::Get()->addComment(
                'shop-history-user-'.$r,
                'Добавлен новый пользователь #'.$r.' '.$x->getName(),
                $user->getId()
                );
            } catch (Exception $e) {

            }

            SQLObject::TransactionCommit();

            return $r;
        } catch (Exception $ge) {
            SQLObject::TransactionRollback();
            throw $ge;
        }
    }

    public function update($key, $fieldsArray) {
        try {
            SQLObject::TransactionStart();

            $r = parent::update($key, $fieldsArray);

            try {
                $user = BC::Get()->getUserService()->getUser();

                $x = BC::Get()->getUserService()->getUserByID($key);

                $diffArray = array();
                foreach ($fieldsArray as $field) {
                    if ($field->getEditable()) {
                        $diffArray[] = $field->getName().' '.$field->getValue();
                    }
                }

                CommentsAPI::Get()->addComment(
                'shop-history-user-'.$x->getId(),
                'Отредактирован пользователь #'.$x->getId().' '.$x->getName()."\n".implode("\n", $diffArray),
                $user->getId()
                );
            } catch (Exception $e) {

            }

            SQLObject::TransactionCommit();

            return $r;
        } catch (Exception $ge) {
            SQLObject::TransactionRollback();
            throw $ge;
        }
    }

    public function delete($key) {
        // удалять юзеров нельзя,
        // можно только банить

        try {
            $x = BC::Get()->getUserService()->getUserByID($key);
            $x->setLevel(0);
            $x->update();

            try {
                $user = BC::Get()->getUserService()->getUser();

                CommentsAPI::Get()->addComment(
                'shop-history-user-'.$x->getId(),
                'Заблокирован пользователь #'.$x->getId().' '.$x->getLogin(),
                $user->getId()
                );
            } catch (Exception $e) {

            }
        } catch (Exception $e) {

        }
    }

    private $_groupID = false;

}